package cn.jasonone.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.jasonone.bean.SysRole;
import cn.jasonone.bean.SysUser;
import cn.jasonone.service.SysRoleService;
import cn.jasonone.service.SysUserService;

@RestController
@RequestMapping("/user")
public class SysUserController {
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysRoleService roleService;
	

	@GetMapping
	public ModelAndView home() {
		return new ModelAndView("sys/user/index");
	}

	@GetMapping({ "/save", "/save/{id}" })
	public ModelAndView save(@PathVariable(name = "id", required = false) Integer id) {
		ModelAndView modelAndView = new ModelAndView("sys/user/save");
		if (id != null) {
			modelAndView.addObject("user", sysUserService.findById(id));
			modelAndView.addObject("admin", this.roleService.isAdmin(id));
		}
		return modelAndView;
	}

	@PostMapping("/save")
	public Object save(SysUser user,@RequestParam("roleIds[]")int[] roleIds) {
		Map<String, Object> result = new HashMap<>();
		result.put("success", sysUserService.save(user,roleIds));
		return result;
	}

	@GetMapping("/find")
	public Object findAll(SysUser user,
			@RequestParam(defaultValue = "1")int page,
			@RequestParam(defaultValue = "10")int limit
			) {
		PageHelper.startPage(page, limit);
		List<SysUser> list = sysUserService.findAll(user);
		PageInfo<SysUser> pageInfo=new PageInfo<>(list);
		Map<String,Object> result=new HashMap<>();
		result.put("code", 0);
		result.put("msg", "查询成功");
		result.put("count", pageInfo.getTotal());
		result.put("data", pageInfo.getList());
		return result;
	}
	@GetMapping("/del")
	public Object delete(int id) {
		Map<String,Object> result=new HashMap<>();
		result.put("success", true);
		if(this.roleService.isAdmin(id)) {
			result.put("success", false);
			result.put("msg", "超级管理员用户,不能被删除");
		}else if(!this.sysUserService.deleteByIds(id)) {
			result.put("success", false);
			result.put("msg", "删除失败或数据不存在");
		}
		return result;
	}
	
}
